package com.alpha.gateway.filter;

import com.alpha.core.http.HttpConstants;
import com.alpha.core.utils.CollectionUtil;
import com.alpha.core.utils.JsonUtil;
import com.alpha.gateway.service.AuthorizationService;
import com.alpha.gateway.utils.ResponseUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Map;

/**
 * 认证(authentication)、鉴权(authorization)过滤器，检查请求token是否有效，检查用户是否有访问权限
 *
 * @author chenruwan
 * @since 2022-01-01
 */
@Component
@RequiredArgsConstructor
public class AlphaAuthFilter implements GlobalFilter, Ordered {

    private final AuthorizationService authorizationService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();

        if (authorizationService.isWhitelists(request)) {
            return chain.filter(exchange);
        }

        Map<String, Object> claims = JsonUtil.toMap(request.getHeaders().getFirst(HttpConstants.CLAIMS));
        if (CollectionUtil.isEmpty(claims)) {
            return ResponseUtil.response(exchange, HttpStatus.UNAUTHORIZED, "未登录或登录已过期，请重新登录");
        }

        if (!authorizationService.hasAuthority(String.valueOf(claims.get(HttpConstants.CLAIM_USER_ID)), request)) {
            return ResponseUtil.response(exchange, HttpStatus.FORBIDDEN, "没有访问权限");
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -3;
    }
}
